package jdklearning.concurrent.thread.interrupt;


import java.util.concurrent.locks.ReentrantLock;

/**
 * 一看到线程的interrupt()方法，根据字面意思，很容易将该方法理解为中断线程
 * 。其实Thread.interrupt()并不会中断线程的运行，它的作用仅仅是为线程设定一个状态而已
 * ，即标明线程是中断状态，这样线程的调度机制或我们的代码逻辑就可以通过判断这个状态做一些处理
 * ，比如sleep()方法会抛出异常，或是我们根据isInterrupted()方法判断线程是否处于中断状态，然后做相关的逻辑处理。
 *
 *
 * interrupt, 只是给线程发个信号，如果在wait, sleep,lockInterruptibly会收到exception
 * @author shenenlu 2021年02月20日 上午09:48:53
 */
public class InterruptLearning2 {


    /**
     * lockInterruptibly可以响应interrupt,lock不可以
     * @throws InterruptedException
     */
    public static void interruptReentrantLock() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                lock.lock();
                while (true){
                    long start = System.currentTimeMillis();
                    Thread t = currentThread();
                    System.out.println( t.getName() + ":"
                            + t.isInterrupted() );
//                        Thread.sleep(3000);
                    for(;;){
                        if( System.currentTimeMillis() - start > 3000){
                            break;
                        }
                    }
                }
            }
        };
        Thread t2 = new Thread("t2"){
            @Override
            public void run() {
                try {
//                    lock.lock();
                    lock.lockInterruptibly();
                    while (true){
                        Thread t = currentThread();
                        System.out.println(t.getName()+":"
                                +t.isInterrupted());
                        Thread.sleep(3000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        };
        t2.start();
        Thread.sleep(100);
        t1.start();
        Thread.sleep(10000);
        t2.interrupt();
        Thread.sleep(10000);
        t1.interrupt();
    }



    


    public static void main(String[] args) throws InterruptedException {
        interruptReentrantLock();
    }



}
